package process;

import cn.itcast.flink.process.FlinkSQL_Table_Demo02;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.types.Row;

import static org.apache.flink.table.api.Expressions.$;

/**
 * @author ChinaManor
 * #Description Table_Demo01
 * #Date: 22/6/2021 11:47
 */
public class Table_Demo02 {
    public static void main(String[] args) throws Exception {
        //1.准备环境 获取流执行环境 流表环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);

        //2.Source 获取 单词信息
        DataStream<FlinkSQL_Table_Demo02.WC> input = env.fromElements(
                new FlinkSQL_Table_Demo02.WC("Hello", 1),
                new FlinkSQL_Table_Demo02.WC("World", 1),
                new FlinkSQL_Table_Demo02.WC("Hello", 1)
        );

        //3.创建视图 WordCount
        tEnv.createTemporaryView("wordCount",input,$("word"),$("frequency"));
        //4.执行查询 单词统计
        Table resultTable = tEnv.sqlQuery("SELECT word,SUM(frequency) FROM wordCount GROUP BY word ");
        //5.输出结果 retractStream获取数据流（别名）
        resultTable.printSchema();
        //6.打印输出结果
        DataStream<Tuple2<Boolean, Row>> stream = tEnv.toRetractStream(resultTable, Row.class);

        //7.执行
        stream.print();
        env.execute();
    }
}
